package cn.uncode.springcloud.starter.fuse.sentinel;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;

import cn.uncode.springcloud.starter.web.result.R;
import cn.uncode.springcloud.utils.rest.ResultUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 对于sentinel-dashboard内配置的URL的限流和降级进行处理
 * 需要使用WebCallbackManager.setUrlBlockHandler(new CustomUrlBlockHandler());注册
 *
 * @auth:qiss
 * @see: [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Slf4j
public class CustomUrlBlockHandler implements UrlBlockHandler {

    @Override
    public void blocked(HttpServletRequest request, HttpServletResponse response, BlockException ex) throws IOException {
        if (ex instanceof DegradeException) {
            //降级
            log.error("Oops degrade: " + ex.getClass().getCanonicalName(), ex);
            ResultUtil.writeJavaScript(response, R.failure("blocked by flow degrade!"));
        } else {
            //限流
            log.error("Oops limiting: " + ex.getClass().getCanonicalName(), ex);
            ResultUtil.writeJavaScript(response, R.failure("blocked by flow limiting!"));
        }
    }
}
